package com.physics.mps.module.comsol.controller;

import cn.hutool.core.io.IoUtil;
import com.physics.mps.common.config.properties.ApiProperties;
import com.physics.mps.common.exception.BusinessException;
import com.physics.mps.entity.vo.api.Result;
import com.physics.mps.entity.vo.api.UploadVo;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @author mcsoft
 * @date 2023/11/28 10:28
 * @email kuun993@163.com
 * @description TODO
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/temp")
public class TempController {


    private final ApiProperties apiProperties;


    private static final String ROOT = "d:/opt/temp/";

    private static final String ROOT_FORMAT = ROOT + "%s";

    private static final String URL_FORMAT = "http://%s:%s/temp/download/%s";


    @PostMapping("/upload")
    public Result<UploadVo> upload(@RequestPart("file") MultipartFile file) {
        String filename = UUID.randomUUID().toString();
        String filePath = String.format(ROOT_FORMAT, filename);
        try (OutputStream outputStream = Files.newOutputStream(Paths.get(filePath));
             InputStream inputStream = file.getInputStream()) {
            IoUtil.copy(inputStream, outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
        UploadVo uploadVo = new UploadVo();
        uploadVo.setName(filename);
        uploadVo.setUrl(String.format(URL_FORMAT, apiProperties.getIp(), apiProperties.getPort(), filename));
        return Result.success(uploadVo);
    }


    @GetMapping("/download/{filename}")
    public void download(@PathVariable("filename") String filename, HttpServletResponse response) {
        Path filePath = Paths.get(ROOT + filename);
        try(InputStream inputStream = Files.newInputStream(filePath);
            OutputStream outputStream = response.getOutputStream()) {
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + URLEncoder.encode(filePath.getFileName().toString(), "UTF-8"));
            IoUtil.copy(inputStream, outputStream);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

}
